<template>
  <basic-container>
    <el-tabs type="border-card" class="informationLabel">
      <el-tab-pane label="MES库存和ERP对账"></el-tab-pane>
      <avue-form ref="from" :option="formOption" v-model="form">
        <template slot-scope="{}" slot="dimension">
          <div class="form-content">
            <el-radio label="MATERIAL" v-model="form.checkDimensionality" true-label="MATERIAL">所有(物料)</el-radio>
            <div class="warehouse-option mt20">
              <el-radio label="INVENTORY" v-model="form.checkDimensionality" true-label="INVENTORY">仓库</el-radio>
              <div v-if="form.checkDimensionality === 'INVENTORY'" class="warehouse">
                <label>仓库:</label>
                <el-input placeholder="请选择 仓库" v-model="form.warehouseName" class="input-with-select" clearable @clear="form.inventoryIds = ''">
                  <el-button slot="append" icon="el-icon-search" @click="openWarehouseModal"></el-button>
                </el-input>
              </div>
            </div>
            <div class="mt20">
              <el-button type="primary" size="small" @click="handleReconciliation">执行对账 </el-button>
              <span class="ml20">备注：建议是在ERP关账时间段内执行对账!</span>
            </div>
          </div>
        </template>
        <template slot-scope="{}" slot="result">
          <div class="result-container">
            <div class="result-item">对账笔数:{{ form.checkCount }}</div>
            <div class="result-item">相符笔数:{{ form.matchCount }}</div>
            <div class="result-item">不相符笔数:{{ form.notMatchCount }}</div>
          </div>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="informationLabel mt20">
      <el-tab-pane :label="tabTitle"></el-tab-pane>
      <avue-crud
        :option="option"
        :table-loading="loading"
        v-model="TableForm"
        :page.sync="page"
        :data="data"
        :before-open="beforeOpen"
        ref="crud"
        @row-update="rowUpdate"
        @row-save="rowSave"
        @row-del="rowDel"
        @search-change="searchChange"
        @search-reset="searchReset"
        @current-change="currentChange"
        @size-change="sizeChange"
        @refresh-change="refreshChange"
      >
        <template slot="menuLeft">
          <el-button type="primary" size="small" @click="handleExportDetail('difference')">导出差异明细 </el-button>
          <el-button type="primary" size="small" @click="handleExportDetail('all')">导出全部明细 </el-button>
        </template>
      </avue-crud>
    </el-tabs>

    <common-modal-template ref="commonModalTemplate" :option="modelOption" @getSelectedRows="getSelectedRows"></common-modal-template>
    <export-comp
      v-if="isShowExport"
      ref="exportComp"
      page-api-url="mes-warehouse/erpinventorycheckdetail/page"
      :option="option"
      :page="page"
      :query="exportParams"
      :file-name="exportTitle"
      @close="isShowExport = true"
    >
    </export-comp>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportComp from '@/components/export-comp/index';
import { executeReconciliation, getReconciliation, getReconciliationList } from '@/api/warehouse/erpReconciliation';
export default {
  name: 'erpReconciliation',
  components: {
    CommonModalTemplate,
    exportComp
  },
  watch: {
    'form.checkDimensionality'(val) {
      this.form.inventoryIds = [];
      this.form.warehouseName = '';
      const baseColumn = [
        {
          label: '物料编码',
          prop: 'partNo'
        },
        {
          label: '物料名称',
          prop: 'partName'
        },
        {
          label: '物料规格',
          prop: 'partModel'
        },
        {
          label: 'MES数量',
          prop: 'mesQuantity'
        },
        {
          label: 'ERP数量',
          prop: 'erpQuantity'
        },
        {
          label: '对账结果',
          prop: 'checkResult',
          type: 'select',
          dicData: [
            { label: '相符', value: '' },
            { label: '不相符', value: 'DISCREPANCY' }
          ]
        },
        {
          label: '数量差异',
          prop: 'discrepancyQuantity'
        },
        {
          label: '对账时间',
          prop: 'checkTime'
        }
      ];
      if (val === 'MATERIAL') {
        this.$set(this.option, 'column', baseColumn);
      } else {
        baseColumn.unshift({
          label: '仓库',
          prop: 'inventoryName'
        });
        this.$set(this.option, 'column', baseColumn);
      }
      this.$refs.crud.refreshTable();
    }
  },
  data() {
    return {
      form: {
        checkDimensionality: 'MATERIAL',
        warehouseName: ''
      },
      isShowExport: false,
      exportTitle: '',
      exportParams: {},
      executeId: '',
      modelOption: {},
      query: {},
      tableForm: {},
      formOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '40',
        group: [
          {
            label: '对账维度',
            icon: 'el-icon-vertical-bar',
            arrow: false,
            border: false,
            column: [
              {
                label: '',
                prop: 'dimension'
              }
            ]
          },
          {
            label: '对账结果',
            arrow: false,
            icon: 'el-icon-vertical-bar',
            column: [
              {
                label: '',
                prop: 'result'
              }
            ]
          }
        ]
      },
      loading: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      option: {
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        refreshBtn: false,
        menu: false,
        column: [
          {
            label: '物料编码',
            prop: 'partNo'
          },
          {
            label: '物料名称',
            prop: 'partName'
          },
          {
            label: '物料规格',
            prop: 'partModel'
          },
          {
            label: 'MES数量',
            prop: 'mesQuantity'
          },
          {
            label: 'ERP数量',
            prop: 'erpQuantity'
          },
          {
            label: '对账结果',
            prop: 'checkResult',
            type: 'select',
            dicData: [
              { label: '相符', value: '' },
              { label: '不相符', value: 'DISCREPANCY' }
            ]
          },
          {
            label: '数量差异',
            prop: 'discrepancyQuantity'
          },
          {
            label: '对账时间',
            prop: 'checkTime'
          }
        ]
      }
    };
  },
  mounted() {},
  computed: {
    ...mapGetters(['permission']),
    tabTitle() {
      return this.form.checkDimensionality === 'MATERIAL' ? '物料维度对账差异明细' : '仓库维度对账差异明细';
    }
  },
  methods: {
    rowSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {},
    rowDel(row) {},
    beforeOpen(done, type) {},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },

    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.executeId);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.executeId);
    },
    refreshChange() {
      this.onLoad();
    },
    handleReconciliation() {
      const { checkDimensionality, inventoryIds = [] } = this.form;
      this.$confirm('执行对账后，就会同步ERP此时的【即时库存】，将会进行MES和ERP库存对账对比，请确认是否执行对账？?', '执行对账提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const params = {
          checkDimensionality,
          checkType: 'MANUAL'
        };
        if (checkDimensionality === 'INVENTORY') {
          params.checkDimensionality = 'INVENTORY';
          if (inventoryIds.length > 0) {
            params.inventoryIds = inventoryIds;
          }
        }
        try {
          const res = await executeReconciliation(params);
          if (!res.data.data) {
            this.$message.warning('暂无数据,请重新选择对账维度。');
            return;
          }
          this.executeId = res.data.data;
          await this.getDetail();
          await this.onLoad(this.executeId);
        } catch (e) {
          console.warn(e);
        }
      });
    },
    async getDetail() {
      try {
        const res = await getReconciliation(this.executeId);
        const data = res.data.data;
        const obj = {
          checkCount: data.checkCount || '--',
          matchCount: data.matchCount || '--',
          notMatchCount: data.notMatchCount || '--'
        };
        const form = this._cloneDeep(this.form);
        this.form = Object.assign(form, obj);
      } catch (e) {
        console.warn(e);
      }
    },
    openWarehouseModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modelOption = {
        modalTitle: '选择仓库',
        url: '/api/mes-admin/area/page/storage/management?areaType=WAREHOUSE',
        isPage: true,
        rowSelectionType: 'multiple',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '仓库编码',
            prop: 'code',
            search: true
          },
          {
            label: '仓库名称',
            prop: 'name',
            search: true
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            search: true,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type'
          }
        ]
      };
    },
    getSelectedRows(rowData) {
      this.form.warehouseName = rowData.map((i) => i.name).join(',');
      this.form.inventoryIds = rowData.map((i) => i.id);
      // this.form.id =
    },
    handleExportDetail(type) {
      this.isShowExport = true;
      // 对账没有id返回
      if (!this.executeId) {
        this.$message.warning('暂无数据,请重新选择对账维度。');
        return;
      }
      this.exportTitle = type === 'all' ? 'erp对账全部明细' : 'erp对账差异明细';
      const params = {
        checkResult: type === 'all' ? '' : 'DISCREPANCY',
        inventoryCheckId: this.executeId
      };
      this.exportParams = params;
      this.$refs.exportComp.visible = true;
    },
    async onLoad(id) {
      this.loading = true;
      try {
        const params = Object.assign({ inventoryCheckId: id }, { current: this.page.currentPage, size: this.page.pageSize });
        const res = await getReconciliationList(params);
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.mt20 {
  margin-top: 20px;
}
.ml20 {
  margin-left: 20px;
}
.form_content {
}
.warehouse-option {
  display: flex;
  align-items: center;
  .warehouse {
    display: flex;
    label {
      width: 50px;
      display: block;
    }
  }
}
.result-container {
  display: flex;
  color: red;
  font-size: 14px;
  font-weight: bold;
  .result-item {
    width: 200px;
  }
}
.input-with-select {
  width: 1000px;
}
</style>
